package com.example.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import com.example.silvercare.R;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class SCSocketComm extends Activity {
	Button serverButton;
	Button clientButton;
    StringBuilder mSB1;
    StringBuilder mSB2;
    static public int SEVER_PORT = 7890;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.serverclient);
		
        serverButton = (Button) findViewById(R.id.button1);
        clientButton = (Button) findViewById(R.id.button2);
        serverButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Toast.makeText(SCSocketComm.this, "Local Server is created successfully", Toast.LENGTH_SHORT).show();
		        startService(new Intent("com.example.server.TestService"));
			}
		});

        clientButton.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
		        try {
		        	InetAddress host = InetAddress.getLocalHost();
	                Socket socket = new Socket(host.getHostName(),SEVER_PORT);
	                //outgoing stream redirect to socket
	                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
	                oos.writeObject("Hello There...");
	                
	                ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
	                String message = (String) ois.readObject();
	                Log.d("Tcp Example", "From server: "+message);
	                //Close connection
	                Toast.makeText(SCSocketComm.this, "Connect to local server successfully", Toast.LENGTH_SHORT).show();
	                socket.close();

		        } catch (UnknownHostException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (IOException e) {
	                // TODO Auto-generated catch block
	                e.printStackTrace();
		        } catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});        

	}

}
